/*
 * This program is free software: you can redistribute it and/or modify it under the terms of the 
 * GNU Affero General Public License as published by the Free Software Foundation, either version 3 
 * of the License, or (at your option) any later version.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3, 
 * the Appropriate Legal Notices must display the following words on all interactive user interfaces: 
 * "Copyright (C) 2005-2011 SplendidCRM Software, Inc. All rights reserved."
 */

var sLIST_VIEW_SORT_FIELD       = 'NAME';
var sLIST_VIEW_SORT_DIRECTION   = 'asc';
var sLIST_VIEW_MODULE_NAME      = '';
var sLIST_VIEW_GRID_NAME        = '';
var sLIST_VIEW_SEARCH_FILTER    = '';
// 10/06/2011 Paul.  The ListView enable selection needs to be a global flag. 
var bLIST_VIEW_ENABLE_SELECTION = true;
var cbListViewUI_Main_Clicked   = null;

function ListViewUI_Clear(sLayoutPanel, sMODULE_NAME)
{
	try
	{
		var divMainLayoutPanel = document.getElementById(sLayoutPanel);
		if ( divMainLayoutPanel != null && divMainLayoutPanel.childNodes != null )
		{
			while ( divMainLayoutPanel.childNodes.length > 0 )
			{
				divMainLayoutPanel.removeChild(divMainLayoutPanel.firstChild);
			}
		}
		if ( divMainLayoutPanel == null )
		{
			alert('ListViewUI_Clear: ' + sLayoutPanel + ' does not exist');
			return;
		}
		SplendidUI_ListHeader(sLayoutPanel, sMODULE_NAME + '.LBL_LIST_FORM_TITLE');
		// <table id="ctlListView_grdMain" class="listView" cellspacing="1" cellpadding="3" rules="all" border="0" border="1" width="100%">
		var ctlListView_grdMain = document.createElement('table');
		ctlListView_grdMain.id        = sLayoutPanel + '_ctlListView_grdMain';
		ctlListView_grdMain.width     = '100%';
		ctlListView_grdMain.className = 'listView';
		divMainLayoutPanel.appendChild(ctlListView_grdMain);
	}
	catch(e)
	{
		SplendidError.SystemMessage(SplendidError.FormatError(e, 'ListViewUI_Clear'));
	}
}

function ListViewUI_Reset(sLayoutPanel, sMODULE_NAME)
{
	try
	{
		sLIST_VIEW_SORT_FIELD     = 'NAME';
		sLIST_VIEW_SORT_DIRECTION = 'asc';
		sLIST_VIEW_SEARCH_FILTER  = '';
		ListViewUI_Clear(sLayoutPanel, sMODULE_NAME);
	}
	catch(e)
	{
		SplendidError.SystemMessage(SplendidError.FormatError(e, 'ListViewUI_Reset'));
	}
}

function ListViewUI_Sort(sLayoutPanel, sActionsPanel, sFIELD_NAME, sDIRECTION)
{
	try
	{
		sLIST_VIEW_SORT_FIELD     = sFIELD_NAME;
		sLIST_VIEW_SORT_DIRECTION = sDIRECTION;
		SplendidError.SystemMessage('Sorting ' + sFIELD_NAME + ' ' + sDIRECTION);
		var bgPage = chrome.extension.getBackgroundPage();
		// 10/04/2011 Paul.  The session might have timed-out, so first check if we are authenticated. 
		bgPage.AuthenticatedMethod(function(status, message)
		{
			if ( status == 1 )
			{
				ListViewUI_LoadModule(sLayoutPanel, sActionsPanel, sLIST_VIEW_MODULE_NAME, sLIST_VIEW_GRID_NAME, sLIST_VIEW_SEARCH_FILTER, function(status, message)
				{
					if ( status == 1 )
					{
						SplendidError.SystemMessage('');
					}
					else
					{
						SplendidError.SystemMessage(message);
					}
				});
			}
			else
			{
				SplendidError.SystemMessage(message);
			}
		});
	}
	catch(e)
	{
		SplendidError.SystemMessage(SplendidError.FormatError(e, 'ListViewUI_Sort'));
	}
}

function ListViewUI_Search(sLayoutPanel, sActionsPanel, sFilter)
{
	try
	{
		//alert('ListViewUI_Search ' + dumpObj(arrData, 'arrData'));
		SplendidError.SystemMessage('Searching ');
		sLIST_VIEW_SEARCH_FILTER = sFilter;
		//alert('ListViewUI_Search ' + sLIST_VIEW_SEARCH_FILTER);
		var bgPage = chrome.extension.getBackgroundPage();
		// 10/04/2011 Paul.  The session might have timed-out, so first check if we are authenticated. 
		bgPage.AuthenticatedMethod(function(status, message)
		{
			if ( status == 1 )
			{
				ListViewUI_LoadModule(sLayoutPanel, sActionsPanel, sLIST_VIEW_MODULE_NAME, sLIST_VIEW_GRID_NAME, sLIST_VIEW_SEARCH_FILTER, function(status, message)
				{
					if ( status == 1 )
					{
						//SplendidError.SystemMessage(sLIST_VIEW_SEARCH_FILTER);
						SplendidError.SystemMessage('');
					}
					else
					{
						SplendidError.SystemMessage(message);
					}
				});
			}
			else
			{
				SplendidError.SystemMessage(message);
			}
		});
	}
	catch(e)
	{
		SplendidError.SystemMessage(SplendidError.FormatError(e, 'ListViewUI_Search'));
	}
}

function ListViewUI_CheckAll(chkMainCheckAll, sFieldID)
{
	try
	{
		var fld = document.getElementsByName(sFieldID);
		for (var i = 0; i < fld.length; i++)
		{
			if ( fld[i].type == 'checkbox' )
			{
				fld[i].checked = chkMainCheckAll.checked;
				if( fld[i].onclick != null )
				{
					fld[i].onclick();
				}
			}
		}
	}
	catch(e)
	{
		SplendidError.SystemAlert(e, 'ListViewUI_CheckAll');
	}
}

function ListViewUI_RenderHeader(sLayoutPanel, sActionsPanel, layout, tbody)
{
	// <tr class="listViewThS1">
	var tr = document.createElement('tr');
	tbody.appendChild(tr);
	tr.className = 'listViewThS1';
	if ( layout.length > 0 )
	{
		// 09/01/2011 Paul.  First column will be for actions. 
		var td = document.createElement('td');
		tr.appendChild(td);
		if ( cbListViewUI_Main_Clicked != null )
		{
			var chkMainCheckAll = document.createElement('input');
			chkMainCheckAll.id        = 'chkMainCheckAll';
			chkMainCheckAll.name      = 'chkMainCheckAll';
			chkMainCheckAll.type      = 'checkbox';
			chkMainCheckAll.className = 'checkbox';
			chkMainCheckAll.onclick   = BindArguments(ListViewUI_CheckAll, chkMainCheckAll, 'chkMain');
			chkMainCheckAll.style.padding       = '2';
			chkMainCheckAll.style.verticalAlign = 'middle';
			td.appendChild(chkMainCheckAll);
		}
		var bEnableTeamManagement = Crm.Config.enable_team_management();
		var bEnableDynamicTeams   = Crm.Config.enable_dynamic_teams();
		for ( var nLayoutIndex in layout )
		{
			var lay = layout[nLayoutIndex];
			//alert(dumpObj(lay, 'lay'));
			var sCOLUMN_TYPE                = lay.COLUMN_TYPE               ;
			var sHEADER_TEXT                = lay.HEADER_TEXT               ;
			var sSORT_EXPRESSION            = lay.SORT_EXPRESSION           ;
			var sITEMSTYLE_WIDTH            = lay.ITEMSTYLE_WIDTH           ;
			var sITEMSTYLE_CSSCLASS         = lay.ITEMSTYLE_CSSCLASS        ;
			var sITEMSTYLE_HORIZONTAL_ALIGN = lay.ITEMSTYLE_HORIZONTAL_ALIGN;
			var sITEMSTYLE_VERTICAL_ALIGN   = lay.ITEMSTYLE_VERTICAL_ALIGN  ;
			var sITEMSTYLE_WRAP             = lay.ITEMSTYLE_WRAP            ;
			var sDATA_FIELD                 = lay.DATA_FIELD                ;
			var sDATA_FORMAT                = lay.DATA_FORMAT               ;
			var sURL_FIELD                  = lay.URL_FIELD                 ;
			var sURL_FORMAT                 = lay.URL_FORMAT                ;
			var sURL_TARGET                 = lay.URL_TARGET                ;
			var sLIST_NAME                  = lay.LIST_NAME                 ;
			var sURL_MODULE                 = lay.URL_MODULE                ;
			var sURL_ASSIGNED_FIELD         = lay.URL_ASSIGNED_FIELD        ;
			var sVIEW_NAME                  = lay.VIEW_NAME                 ;
			var sMODULE_NAME                = lay.MODULE_NAME               ;
			var sMODULE_TYPE                = lay.MODULE_TYPE               ;
			var sPARENT_FIELD               = lay.PARENT_FIELD              ;
			
			// <td style="white-space:nowrap;"><a href="javascript:ListViewUI_Sort('NAME')">Name</a></td>
			td = document.createElement('td');
			tr.appendChild(td);
			if ( (sDATA_FIELD == 'TEAM_NAME' || sDATA_FIELD == 'TEAM_SET_NAME') )
			{
				if ( bEnableTeamManagement && bEnableDynamicTeams )
				{
					sHEADER_TEXT = '.LBL_LIST_TEAM_SET_NAME';
					sDATA_FIELD  = 'TEAM_SET_NAME';
				}
				else if ( !bEnableTeamManagement )
				{
					td.style.display = 'none';
				}
			}
			
			if ( sSORT_EXPRESSION != null )
			{
				var a = document.createElement('a');
				td.appendChild(a);
				a.innerHTML = '<nobr>' + L10n.Term(sHEADER_TEXT) + '</nobr>';
				var img = document.createElement('img');
				td.appendChild(img);
				img.align       = 'absmiddle';
				img.height      = 10;
				img.width       = 8;
				img.borderWidth = 0;
				if ( sSORT_EXPRESSION == sLIST_VIEW_SORT_FIELD )
				{
					// img src="../App_Themes/Six/images/arrow_up.gif" align="absmiddle" style="border-width:0px;height:10px;width:8px;" />
					if ( sLIST_VIEW_SORT_DIRECTION == 'asc' )
					{
						img.src = sIMAGE_SERVER + 'App_Themes/Six/images/arrow_up.gif';
						a.href = 'javascript:ListViewUI_Sort("' + sLayoutPanel + '", "' + sActionsPanel + '", "' + sSORT_EXPRESSION + '", "desc")';
					}
					else
					{
						img.src = sIMAGE_SERVER + 'App_Themes/Six/images/arrow_down.gif';
						a.href = 'javascript:ListViewUI_Sort("' + sLayoutPanel + '", "' + sActionsPanel + '", "' + sSORT_EXPRESSION + '", "asc")';
					}
				}
				else
				{
					// img src="../App_Themes/Six/images/arrow.gif" align="absmiddle" style="border-width:0px;height:10px;width:8px;" />
					img.src = sIMAGE_SERVER + 'App_Themes/Six/images/arrow.gif';
					a.href = 'javascript:ListViewUI_Sort("' + sLayoutPanel + '", "' + sActionsPanel + '", "' + sSORT_EXPRESSION + '", "asc")';
				}
			}
			else if ( sHEADER_TEXT != null )
			{
				var txt = document.createTextNode('<nobr>' + L10n.Term(sHEADER_TEXT) + '</nobr>');
				td.appendChild(txt);
			}
		}
	}
}

function ListViewUI_RenderRow(sLayoutPanel, sActionsPanel, sLIST_MODULE_NAME, layout, tr, row)
{
	if ( layout.length > 0 )
	{
		// 09/01/2011 Paul.  First column will be for actions. 
		var td = document.createElement('td');
		tr.appendChild(td);
		td.style.whiteSpace = 'nowrap';

		if ( cbListViewUI_Main_Clicked != null )
		{
			// 11/27/2011 Paul.  IE has a problem setting the Name when it does not match the ID. 
			// http://webbugtrack.blogspot.com/2007/10/bug-235-createelement-is-broken-in-ie.html
			var chkMain = null;
			// 11/27/2011 Paul.  Detect Internet Explorer. http://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx
			if ( navigator.appName == 'Microsoft Internet Explorer' )
				chkMain = document.createElement('<input name="chkMain" />');
			else
				chkMain = document.createElement('input');
			chkMain.id        = 'chkMain_' + Sql.ToString(row['ID']).replace('-', '_');
			chkMain.name      = 'chkMain';
			chkMain.type      = 'checkbox';
			chkMain.className = 'checkbox';
			chkMain.Module    = sLIST_MODULE_NAME;
			chkMain.value     = row['ID'  ];
			chkMain.tooltip   = row['NAME'];
			chkMain.onclick   = BindArguments(cbListViewUI_Main_Clicked, chkMain, sLIST_MODULE_NAME, row['ID'], row['NAME']);
			chkMain.style.padding       = '2';
			chkMain.style.verticalAlign = 'middle';
			// 09/25/2011 Paul.  IE does not allow you to set the type after it is added to the document. 
			td.appendChild(chkMain);
			// 10/04/2011 Paul.  IE8 requires that we set checked after appending. 
			if ( SelectionUI_IsSelected(row['ID']) )
				chkMain.checked = true;
		}

		var aView = document.createElement('a');
		td.appendChild(aView);
		aView.href      = 'javascript:DetailViewUI_Load("' + sLayoutPanel + '", "' + sActionsPanel + '", "' + sLIST_MODULE_NAME + '", "' + row['ID'] + '")';
		
		var imgView = document.createElement('img');
		aView.appendChild(imgView);
		imgView.align       = 'absmiddle';
		imgView.height      = 16;
		imgView.width       = 16;
		imgView.borderWidth = 0;
		imgView.src         = sIMAGE_SERVER + 'App_Themes/Six/images/view_inline.gif';
		imgView.alt         = L10n.Term('.LNK_VIEW');
		imgView.style.padding = '2';
		imgView.style.border  = 'none';

		var aEdit = document.createElement('a');
		td.appendChild(aEdit);
		aEdit.href      = 'javascript:EditViewUI_Load("' + sLayoutPanel + '", "' + sActionsPanel + '", "' + sLIST_MODULE_NAME + '", "' + row['ID'] + '", false)';
		
		var imgEdit = document.createElement('img');
		aEdit.appendChild(imgEdit);
		imgEdit.align       = 'absmiddle';
		imgEdit.height      = 16;
		imgEdit.width       = 16;
		imgEdit.borderWidth = 0;
		imgEdit.src         = sIMAGE_SERVER + 'App_Themes/Six/images/edit_inline.gif';
		imgEdit.alt         = L10n.Term('.LNK_EDIT');
		imgEdit.style.padding = '2';
		imgEdit.style.border  = 'none';
		
		var bEnableTeamManagement = Crm.Config.enable_team_management();
		var bEnableDynamicTeams   = Crm.Config.enable_dynamic_teams();
		for ( var nLayoutIndex in layout )
		{
			var lay = layout[nLayoutIndex];
			//alert(dumpObj(lay, 'lay'));
			var sCOLUMN_TYPE                = lay.COLUMN_TYPE               ;
			var sHEADER_TEXT                = lay.HEADER_TEXT               ;
			var sSORT_EXPRESSION            = lay.SORT_EXPRESSION           ;
			var sITEMSTYLE_WIDTH            = lay.ITEMSTYLE_WIDTH           ;
			var sITEMSTYLE_CSSCLASS         = lay.ITEMSTYLE_CSSCLASS        ;
			var sITEMSTYLE_HORIZONTAL_ALIGN = lay.ITEMSTYLE_HORIZONTAL_ALIGN;
			var sITEMSTYLE_VERTICAL_ALIGN   = lay.ITEMSTYLE_VERTICAL_ALIGN  ;
			var sITEMSTYLE_WRAP             = lay.ITEMSTYLE_WRAP            ;
			var sDATA_FIELD                 = lay.DATA_FIELD                ;
			var sDATA_FORMAT                = lay.DATA_FORMAT               ;
			var sURL_FIELD                  = lay.URL_FIELD                 ;
			var sURL_FORMAT                 = lay.URL_FORMAT                ;
			var sURL_TARGET                 = lay.URL_TARGET                ;
			var sLIST_NAME                  = lay.LIST_NAME                 ;
			var sURL_MODULE                 = lay.URL_MODULE                ;
			var sURL_ASSIGNED_FIELD         = lay.URL_ASSIGNED_FIELD        ;
			var sVIEW_NAME                  = lay.VIEW_NAME                 ;
			var sMODULE_NAME                = lay.MODULE_NAME               ;
			var sMODULE_TYPE                = lay.MODULE_TYPE               ;
			var sPARENT_FIELD               = lay.PARENT_FIELD              ;
			
			td = document.createElement('td');
			tr.appendChild(td);
			if ( (sDATA_FIELD == 'TEAM_NAME' || sDATA_FIELD == 'TEAM_SET_NAME') )
			{
				if ( bEnableTeamManagement && bEnableDynamicTeams )
				{
					sHEADER_TEXT = '.LBL_LIST_TEAM_SET_NAME';
					sDATA_FIELD  = 'TEAM_SET_NAME';
				}
				else if ( !bEnableTeamManagement )
				{
					td.style.display = 'none';
				}
			}
			
			if ( sITEMSTYLE_WIDTH            != null ) td.width     = sITEMSTYLE_WIDTH           ;
			if ( sITEMSTYLE_CSSCLASS         != null ) td.className = sITEMSTYLE_CSSCLASS        ;
			if ( sITEMSTYLE_HORIZONTAL_ALIGN != null ) td.align     = sITEMSTYLE_HORIZONTAL_ALIGN;
			if ( sITEMSTYLE_VERTICAL_ALIGN   != null ) td.vAlign    = sITEMSTYLE_VERTICAL_ALIGN  ;
			
			if (   sCOLUMN_TYPE == 'BoundColumn' 
			    && (   sDATA_FORMAT == 'Date'
			        || sDATA_FORMAT == 'DateTime'
			        || sDATA_FORMAT == 'Currency'
			        || sDATA_FORMAT == 'Image'
			        || sDATA_FORMAT == 'MultiLine'
			       )
			   )
			{
				sCOLUMN_TYPE = 'TemplateColumn';
			}
			if ( sCOLUMN_TYPE == 'TemplateColumn' )
			{
				if ( row[sDATA_FIELD] != null )
				{
					if ( sDATA_FORMAT == 'HyperLink' && row[sURL_FIELD] != null )
					{
						var a = document.createElement('a');
						td.appendChild(a);
						if ( sURL_FORMAT.indexOf('view.aspx?id=') > 0 )
							a.href      = 'javascript:DetailViewUI_Load("' + sLayoutPanel + '", "' + sActionsPanel + '", "' + sURL_MODULE + '", "' + row[sURL_FIELD] + '")';
						else if ( sURL_FORMAT.indexOf('edit.aspx?id=') > 0 )
							a.href      = 'javascript:EditViewUI_Load("' + sLayoutPanel + '", "' + sActionsPanel + '", "' + sURL_MODULE + '", "' + row[sURL_FIELD] + '", false)';
						a.innerHTML = row[sDATA_FIELD];
					}
					else if ( sDATA_FORMAT == 'Date' )
					{
						var sDATA_VALUE = row[sDATA_FIELD];
						sDATA_VALUE = FromJsonDate(sDATA_VALUE, Security.USER_DATE_FORMAT());
						td.innerHTML = sDATA_VALUE;
					}
					else if ( sDATA_FORMAT == 'DateTime' )
					{
						var sDATA_VALUE = row[sDATA_FIELD];
						sDATA_VALUE = FromJsonDate(sDATA_VALUE, Security.USER_DATE_FORMAT() + ' ' + Security.USER_TIME_FORMAT());
						td.innerHTML = sDATA_VALUE;
					}
					else if ( sDATA_FORMAT == 'Currency' )
					{
						var sDATA_VALUE = row[sDATA_FIELD];
						td.innerHTML = sDATA_VALUE;
					}
					else if ( sDATA_FORMAT == 'MultiLine' )
					{
						var sDATA_VALUE = row[sDATA_FIELD];
						td.innerHTML = sDATA_VALUE;
					}
					else if ( sDATA_FORMAT == 'Image' )
					{
					}
					else if ( sDATA_FORMAT == 'JavaScript' )
					{
					}
					else if ( sDATA_FORMAT == 'Hover' )
					{
					}
				}
			}
			else if ( sCOLUMN_TYPE == 'BoundColumn' )
			{
				if ( row[sDATA_FIELD] != null )
				{
					if ( sLIST_NAME != null )
					{
						var sDATA_VALUE = L10n.Term('.' + sLIST_NAME + '.' + row[sDATA_FIELD]);
						// 10/04/2011 Paul.  Testing for NULL does not work, so just check if the list name matches the label. 
						if ( sDATA_VALUE == '.' + sLIST_NAME + '.' )
							sDATA_VALUE = '';
						td.innerHTML = sDATA_VALUE;
					}
					else
					{
						var sDATA_VALUE = row[sDATA_FIELD];
						td.innerHTML = sDATA_VALUE;
					}
				}
			}
		}
	}
}

function ListViewUI_GridColumns(layout)
{
	var arrSelectFields = new Array();
	if ( layout.length > 0 )
	{
		for ( var nLayoutIndex in layout )
		{
			var lay = layout[nLayoutIndex];
			var sSORT_EXPRESSION            = lay.SORT_EXPRESSION           ;
			var sDATA_FIELD                 = lay.DATA_FIELD                ;
			var sDATA_FORMAT                = lay.DATA_FORMAT               ;
			var sURL_FIELD                  = lay.URL_FIELD                 ;
			var sURL_ASSIGNED_FIELD         = lay.URL_ASSIGNED_FIELD        ;
			var sPARENT_FIELD               = lay.PARENT_FIELD              ;
			
			if ( sDATA_FORMAT == 'Hover' )
				continue;
			if ( sDATA_FIELD != null && sDATA_FIELD.length > 0 )
			{
				arrSelectFields.push(sDATA_FIELD);
			}
			if ( sSORT_EXPRESSION != null && sSORT_EXPRESSION.length > 0 )
			{
				if ( sDATA_FIELD != sSORT_EXPRESSION )
					arrSelectFields.push(sSORT_EXPRESSION);
			}
			if ( sURL_FIELD != null && sURL_FIELD.length > 0 )
			{
				if ( sURL_FIELD.indexOf(' ') >= 0 )
				{
					var arrURL_FIELD = sURL_FIELD.split(' ');
					for ( var i in arrURL_FIELD )
					{
						var s = arrURL_FIELD[i];
						if ( s.indexOf('.') == -1 && s.length > 0 )
						{
							arrSelectFields.push(s);
						}
					}
				}
				else if ( sURL_FIELD.indexOf('.') == -1 )
				{
					arrSelectFields.push(sURL_FIELD);
				}
				if ( sURL_ASSIGNED_FIELD != null && sURL_ASSIGNED_FIELD.length > 0 )
				{
					arrSelectFields.push(sURL_ASSIGNED_FIELD);
				}
			}
			if ( sPARENT_FIELD != null && sPARENT_FIELD.length > 0 )
			{
				arrSelectFields.push(sPARENT_FIELD);
			}
		}
	}
	return arrSelectFields.join(',');
}

function ListViewUI_LoadModule(sLayoutPanel, sActionsPanel, sMODULE_NAME, sGRID_NAME, sLIST_VIEW_SEARCH_FILTER, callback)
{
	try
	{
		var bgPage = chrome.extension.getBackgroundPage();
		//var layout = bgPage.SplendidCache.GridViewColumns(sGRID_NAME);
		bgPage.ListView_LoadLayout(sGRID_NAME, function(status, message)
		{
			if ( status == 1 )
			{
				// 10/03/2011 Paul. ListView_LoadLayout returns the layout. 
				var layout = message;
				var sSELECT_FIELDS = ListViewUI_GridColumns(layout);
				bgPage.ListView_LoadModule(sMODULE_NAME, sLIST_VIEW_SORT_FIELD, sLIST_VIEW_SORT_DIRECTION, sSELECT_FIELDS, sLIST_VIEW_SEARCH_FILTER, function(status, message)
				{
					if ( status == 1 )
					{
						// 10/04/2011 Paul.  ListView_LoadModule returns the row. 
						var rows = message;
						ListViewUI_Clear(sLayoutPanel, sMODULE_NAME);
						var ctlListView_grdMain = document.getElementById(sLayoutPanel + '_ctlListView_grdMain');
						var tbody = document.createElement('tbody');
						ctlListView_grdMain.appendChild(tbody);
						
						ListViewUI_RenderHeader(sLayoutPanel, sActionsPanel, layout, tbody);
						
						for ( var i = 0; i < rows.length; i++ )
						{
							var tr = document.createElement('tr');
							tbody.appendChild(tr);
							if ( i % 2 == 0 )
								tr.className = 'oddListRowS1';
							else
								tr.className = 'evenListRowS1';
							
							var row = rows[i];
							ListViewUI_RenderRow(sLayoutPanel, sActionsPanel, sMODULE_NAME, layout, tr, row);
						}
						callback(1, null);
					}
					else
					{
						callback(status, message);
					}
				});
			}
			else
			{
				callback(status, message);
			}
		});
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'ListViewUI_LoadModule'));
	}
}

function ListViewUI_Load(sLayoutPanel, sActionsPanel, sMODULE_NAME, sGRID_NAME, rowDefaultSearch, callback)
{
	try
	{
		sLIST_VIEW_MODULE_NAME   = null;
		sLIST_VIEW_GRID_NAME     = null;
		sLIST_VIEW_SEARCH_FILTER = '';
		
		var bgPage = chrome.extension.getBackgroundPage();
		// 11/29/2011 Paul.  We are having an issue with the globals getting reset, so we need to re-initialize. 
		if ( !bgPage.SplendidCache.IsInitialized() )
		{
			SplendidUI_ReInit(sLayoutPanel, sActionsPanel, sMODULE_NAME);
			return;
		}
		
		sLIST_VIEW_MODULE_NAME   = sMODULE_NAME;
		sLIST_VIEW_GRID_NAME     = sGRID_NAME;
		sLIST_VIEW_SEARCH_FILTER = '';
		cbListViewUI_Main_Clicked = bLIST_VIEW_ENABLE_SELECTION ? SelectionUI_chkMain_Clicked : null;

		// 10/04/2011 Paul.  The session might have timed-out, so first check if we are authenticated. 
		bgPage.AuthenticatedMethod(function(status, message)
		{
			if ( status == 1 )
			{
				bgPage.Terminology_LoadModule(sMODULE_NAME, function(status, message)
				{
					if ( status == 0 || status == 1 )
					{
						// 09/10/2011 Paul.  Make sure to load the layout first as it might be needed inside SearchViewUI_SearchForm, or ListViewUI_LoadModule, which run in parallel. 
						bgPage.ListView_LoadLayout(sGRID_NAME, function(status, message)
						{
							if ( status == 1 )
							{
								SplendidUI_ModuleHeader(sLayoutPanel, sActionsPanel, sMODULE_NAME, '.moduleList.Home');
								// 10/03/2011 Paul. ListView_LoadLayout returns the layout. 
								var layout = message;
								SearchViewUI_Load(sLayoutPanel, sActionsPanel, sMODULE_NAME, sMODULE_NAME + '.SearchBasic' + sPLATFORM_LAYOUT, rowDefaultSearch, true, ListViewUI_Search, function(status, message)
								{
									if ( status == 1 )
									{
										//SplendidError.SystemMessage('');
									}
									else
									{
										callback(status, message);
									}
									if ( rowDefaultSearch != null )
									{
										var sEDIT_NAME = sMODULE_NAME + '.SearchBasic' + sPLATFORM_LAYOUT;
										SearchViewUI_SearchForm(sLayoutPanel, sActionsPanel, sEDIT_NAME, ListViewUI_Search);
									}
								});
								if ( rowDefaultSearch == null )
								{
									ListViewUI_LoadModule(sLayoutPanel, sActionsPanel, sMODULE_NAME, sGRID_NAME, sLIST_VIEW_SEARCH_FILTER, function(status, message)
									{
										if ( status == 1 && bLIST_VIEW_ENABLE_SELECTION )
											SelectionUI_Render();
										callback(status, message);
									});
								}
							}
							else
							{
								callback(status, message);
							}
						});
					}
					else
					{
						callback(status, message);
					}
				});
			}
			else
			{
				callback(-1, message);
			}
		});
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'ListViewUI_Load'));
	}
}


